package com.banshuibao.bsb_android.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.model.AdModel;
import com.banshuibao.bsb_android.util.ImageUtil;
import com.banshuibao.bsb_android.util.IntentManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by zyh on 2017/3/17.
 */

public class AdViewPagerAdapter extends PagerAdapter implements ViewPager.OnPageChangeListener {

    private List<ImageView> imageViews;

    private List<ImageView> iconViews;

    private Context context;

    private ViewPager viewPager;

    private Timer timer;

    private static final int INTERVAL = 5000;

    private boolean isScroll;

    private int position;

    private LinearLayout linearLayout;

    private Handler handler;

    public AdViewPagerAdapter(Context context, final ViewPager viewPager) {
        imageViews = new ArrayList<>();
        this.context = context;
        this.viewPager = viewPager;
        viewPager.addOnPageChangeListener(this);
        linearLayout = (LinearLayout) ((FrameLayout) viewPager.getParent()).getChildAt(1);
        handler = new Handler(context.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                viewPager.setCurrentItem(msg.what);
            }
        };
    }

    public void setImageViews(List<AdModel.Data> models) {
        if (this.imageViews != null) {
            this.imageViews.clear();
            if (models != null && models.size() > 0) {
                int size = models.size();
                for (int i = 0; i < size; ++i) {
                    this.imageViews.add(createAd(models.get(i)));
                }
                createWhileList(models);
                notifyDataSetChanged();
                if (size > 1)
                    viewPager.setCurrentItem(1);
            }
        }
    }

    private ImageView createAd(final AdModel.Data data) {
        ImageView imageView = new ImageView(context);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        ImageUtil.loadImage(context, data.getImage(), imageView);
        imageView.setBackground(context.getResources().getDrawable(R.drawable.bsb_b));
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.equals("0", data.getIsNative()))
                    IntentManager.goWebViewActivity(context, data.getTitle(), data.getId(), "pager", "2".equals(data.getIsNative()));
                else {
                    //跳转到竞赛页面
                    if (TextUtils.equals("0", data.getNativeLink())) {
                        IntentManager.goMacthActivity(context);
                    }
                }
            }
        });
        return imageView;
    }

    private void createWhileList(List<AdModel.Data> models) {
        if (imageViews != null && imageViews.size() > 1) {
            initImageIcon();
            imageViews.add(0, createAd(models.get(models.size() - 1)));
            imageViews.add(createAd(models.get(0)));
            initTimer();
        }
    }

    private void initImageIcon() {
        int size = imageViews.size();
        if (iconViews == null)
            iconViews = new ArrayList<>(size);
        else
            iconViews.clear();
        if (linearLayout.getChildCount() != 0)
            linearLayout.removeAllViews();
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER | Gravity.BOTTOM;
        params.setMargins(6, 20, 6, 20);
        for (int i = 0; i < size; i++) {
            ImageView imageView = new ImageView(context);
            imageView.setLayoutParams(params);
            if (i == 0)
                imageView.setImageResource(R.drawable.icon_vp);
            else
                imageView.setImageResource(R.drawable.icon_vp_def);
            iconViews.add(imageView);
            linearLayout.addView(imageView);
        }
    }

    private void initTimer() {
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    if (!isScroll) {
                        if (position >= imageViews.size() - 1)
                            position = 0;
                        handler.sendEmptyMessage(++position);
                    }
                }
            }, INTERVAL, INTERVAL);
        }
    }

    public void stopAuto(boolean b) {
        if (b)
            cancelAuto();
        else
            initTimer();
    }

    private void cancelAuto() {
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void iconChange(int position) {
        int size = iconViews.size();
        if (position < 0)
            position = 0;
        if (position >= size)
            position = size - 1;
        for (int i = 0; i < size; i++) {
            if (position == i)
                iconViews.get(i).setImageResource(R.drawable.icon_vp);
            else
                iconViews.get(i).setImageResource(R.drawable.icon_vp_def);
        }
    }


    @Override
    public int getCount() {
        return imageViews != null ? imageViews.size() : 0;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public View instantiateItem(ViewGroup container, int position) {
        ImageView imageView = imageViews.get(position);
        ViewParent vp = imageView.getParent();
        if (vp != null) {
            ViewGroup parent = (ViewGroup) vp;
            parent.removeView(imageView);
        }
        container.addView(imageViews.get(position));
        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        this.position = position;
        if (imageViews.size() > 1) {
            if (position < 1) {
                viewPager.setCurrentItem(getCount() - 2, false);
            } else if (position > getCount() - 2) {
                viewPager.setCurrentItem(1, false);
            } else
                iconChange(position - 1);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        isScroll = state != ViewPager.SCROLL_STATE_IDLE;
    }

    public void clear() {
        if (imageViews != null) {
            imageViews.clear();
            imageViews = null;
        }
        if (iconViews != null) {
            iconViews.clear();
            iconViews = null;
        }
        cancelAuto();
        handler.removeCallbacksAndMessages(null);
        handler = null;
    }
}
